function transformSpecialChar(str: string) {
  return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

export function loadXML(xmlString: string) {
  const titleReg = /<title>\s*([\s\S]*?)\s*<\/title>/;
  const titleSNReg = /<title>[\s\S]*?SN\s*:\s*(\S*)\s*[\s\S]*<\/title>/;
  const paramReg = /<param[\s\S]*?\/>/g;
  const obj = {
    title: '',
    SN: '',
  };
  if (titleReg.test(xmlString) && RegExp.$1) {
    obj.title = RegExp.$1;
  }
  if (titleSNReg.test(xmlString) && RegExp.$1) {
    obj.SN = transformSpecialChar(RegExp.$1);
  }
  const paramArr = xmlString.match(paramReg);
  if (paramArr?.length) {
    const paramNameReg = /[\s\S]*name\s*=\s*"(\S*)\s*"[\s\S]*\/>/;
    const paramValueReg = /[\s\S]*value\s*=\s*"([\S\s]*)"[\s\S]*\/>/;
    let key: any;
    let value: any;
    paramArr.forEach(param => {
      if (paramNameReg.test(param)) {
        key = RegExp.$1;
      }
      if (paramValueReg.test(param)) {
        value = RegExp.$1;
      }
      if (key && !obj[key] && value) {
        if (key === 'vmm_compress' || key === 'compress') {
          value = parseInt(value, 10);
        }
        obj[key] = value;
      }
    });
  }
  return obj;
}

export function stringToBytes1(str: string) {
  if (typeof str !== 'string') {
    return str;
  }
  let ch;
  const st8 = [0x08];
  const st16 = [0x10];
  let isUtf16 = 0;
  for (let i = 0; i < str.length; i++) {
    ch = str.charCodeAt(i);
    if (ch > 0x00 && ch < 0x80) {
      st8.push(ch & 0xff);
      st16.push(0x00);
      st16.push(ch & 0xff);
    } else {
      st16.push((ch >> 8) & 0xff);
      st16.push(ch & 0xff);
      isUtf16 = 1;
    }
  }
  return isUtf16 === 1 ? st16 : st8;
}
